import React from 'react';
import Api from 'Utils/api';
import { InputItem, ListView } from 'antd-mobile';
import { connect } from 'react-redux';
import { debounce } from 'throttle-debounce';
import * as routerActions from 'react-router-redux';
import { setBusinessInfo } from 'Actions/businessAction';
import './index.scss';

class SelectBusiness extends React.PureComponent {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      searchName: '',
      dataSource: dataSource.cloneWithRows([]),
      isLoading: false,
      listData: [],
      offset: 0,
      hasMore: true,
      totalCount: 0,
      limit: 14,
    };
    this.fetchData = ::this.fetchData;
    this.onEndReached = ::this.onEndReached;
    this.handleSearch = debounce(500, ::this.handleSearch);
    this.selectHandle = ::this.selectHandle;
    this.renderBusinessList = ::this.renderBusinessList;
  }
  // 上拉加载触发函数
  onEndReached() {
    this.setState({ isLoading: true }, () => {
      this.fetchData();
    });
  }
  fetchData() {
    const { searchName, offset, dataSource, limit, } = this.state;
    const self = this;
    const query = {};
    query.limit = limit;
    query.offset = offset;
    query.name_like = searchName;
    const api = new Api({
      method: 'GET',
      path: '/enterprises',
      query,
      success: (json) => {
        if (!json.count) {
          self.setState({
            isLoading: false,
            hasMore: false,
          });
          return;
        }
        self.setState((prevState) => {
          const newListData = [...prevState.listData, ...json.data_list];
          return ({
            totalCount: json.total,
            dataSource: dataSource.cloneWithRows(newListData),
            listData: newListData,
            offset: prevState.offset + json.count,
            isLoading: false,
          });
        });
      },
      error: () => {
        self.setState({
          isLoading: false,
        });
      },
    });
    api.run();
  }
  selectHandle(info) {
    const { dispatch } = this.props;
    dispatch(setBusinessInfo(info));
    dispatch(routerActions.goBack());
  }
  handleSearch(value) {
    this.setState({
      searchName: value,
      isLoading: true,
      offset: 0,
      listData: [],
    }, () => {
      this.fetchData();
    });
  }
  renderBusinessList(data) {
    return (data.length > 0 ? data.map(item => (
      <li className="business-info" onClick={this.selectHandle.bind(this, item)} key={item.id}>
        {item.name}
      </li>
    )) : []);
  }
  renderRow(rowData) {
    return (
      <div className="business-info" onClick={this.selectHandle.bind(this, rowData)}>
        {rowData.name}
      </div>
    )
  }
  render() {
    const { dataSource, limit, totalCount, hasMore, listData } = this.state;
    const row = (rowData) => {
      const obj = rowData;
      if (!obj) {
        return null;
      }
      if (
        this.state.listData.length === totalCount &&
        rowData.id === this.state.listData[this.state.listData.length - 1].id) {
        return (
          <div>
            {
              this.renderRow && this.renderRow(rowData)
            }
            <div className="order-foot">没有更多了</div>
          </div>
        );
      }
      return this.renderRow && this.renderRow(rowData);
    };
    return (
      <div className="select-business-page">
        <div className="search-input-wrap">
          <InputItem
            placeholder="请输入商家名称"
            onChange={this.handleSearch}
          />
        </div>
        <div className="business-list">
          {
            !hasMore && listData.length === 0 ?
              <div className="order-foot-nodata">没有更多了</div> :
              <ListView
                dataSource={dataSource}
                renderFooter={() => (
                  <div>
                    { this.state.isLoading ? <div className="loading-label">加载中...</div> : '' }
                  </div>
                )}
                renderRow={row}
                style={{
                  overflow: 'auto',
                  flexGrow: 1,
                }}
                pageSize={limit}
                className="list"
                initialListSize={limit}
                scrollRenderAheadDistance={500}
                scrollEventThrottle={10}
                onScroll={() => {}}
                onEndReached={this.onEndReached}
                onEndReachedThreshold={10}
              />
          }
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default connect(mapStateToProps)(SelectBusiness);
